package cn.enjoyedu.nettybasic.serializable.msgpack2;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import javax.jws.soap.SOAPBinding;
import java.util.concurrent.atomic.AtomicInteger;

public class MsgPackClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
    private final int sendNumber;

    public MsgPackClientHandler(int sendNumber) {
        this.sendNumber = sendNumber;
    }
    private AtomicInteger counter=new AtomicInteger(0);

    /**
     * <strong>Please keep in mind that this method will be renamed to
     * {@code messageReceived(ChannelHandlerContext, I)} in 5.0.</strong>
     * <p>
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *            belongs to
     * @param msg the message to handle
     * @throws Exception is thrown if an error occurred
     */
    /*客户端读取网络消息后的处理*/
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        String a="";
        System.out.println("client Accept["+msg.toString(CharsetUtil.UTF_8)+"] and the counter is:"+counter.incrementAndGet());
    }

    /**
     * Calls {@link ChannelHandlerContext#fireChannelActive()} to forward
     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx
     */
    /*客户端被通知channel活跃后，做的工作*/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        User[] users = makeUsers();
        for (User user : users) {
            System.out.println("Send user:"+user);
            ctx.write(user);
        }
        ctx.flush();
    }

    /**
     * Calls {@link ChannelHandlerContext#fireExceptionCaught(Throwable)} to forward

     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    /*生成用户实体类的数据组，以供发送*/
    private User[] makeUsers(){
        User[] users=new User[sendNumber];
        User user=null;
        for (int i = 0; i < sendNumber; i++) {
            user=new User();
            user.setAge(i);
            String userName="ABCDEFG----->"+i;
            user.setUserName(userName);
            user.setId("No:"+(sendNumber-i));
            user.setUserContact(new UserContact(userName+"@yangbang.com","123"));
            users[i]=user;
        }
        return users;
    }
}
